var NS = window.NS || {};

NS.IDX = NS.IDX || {};

NS.IDX.MAP = new function () {
    var self = this;
    var myloadingCfg = {
        text: '加载中...',
        color: '#fff',
        textColor: '#fff',
        maskColor: 'rgba(255, 255, 255, 0)',
        zlevel: 0
    };
    var normalAreaColor = "#3ba7dc";
    var emphasisAreaColor = "#f2c34d";
    var navStack = [];
    var areaCodeMap = {
        "衢州市":"100000",

        //衢州市
        "龙游县":   "100000001",


    };

    var stationInArea = {
        /**
         * 龙游县监控中心
         */
        "100000": {
            "stations": [
                {"name": "溪口镇（发射站）", "value": [116.379402,39.920078], "code": "100000001001001"},
                {"name": "横山镇（发射站）", "value": [116.009402,39.820078], "code": "100000001001002"}
            ]
        }
    };

     var areaCodeMapReverse = function (){
        var curMap = new Object();
        $.each(areaCodeMap,function(i,n){
            curMap[n] = i;
        });
        $.each(curMap,function(ci,n){
            if(ci.length == 6){
                if(stationInArea[ci]){
                    $.each(stationInArea[ci].stations,function(i,n){

                        curMap[n.code] = n.name;
                    });
                }
            }
        });
        return curMap;
    }();

    // 基于准备好的dom，初始化echarts实例
    var myChart;

    var option = {
        toolbox: {//工具栏
            // feature: {
            //     myTool1: {
            //         show: true,
            //         title: "返回上级",
            //         icon: "path://M46.627417,61 L115.00347,61 C119.419832,61 123,64.5907123 123,69 C123,73.418278 119.424595,77 115.00347,77 L46.627417,77 L62.6541976,93.0267806 C65.7798592,96.1524422 65.7746915,101.225309 62.6568542,104.343146 C59.5326599,107.46734 54.4654539,107.465454 51.3404891,104.340489 L21.6473176,74.6473176 C18.521656,71.521656 18.5268237,66.4487897 21.6446609,63.3309524 C21.8354653,63.140148 22.033517,62.9610037 22.237931,62.7935188 C22.367853,62.6427543 22.5043153,62.4956847 22.6473176,62.3526824 L52.3404891,32.6595109 C55.4661507,29.5338493 60.539017,29.539017 63.6568542,32.6568542 C66.7810486,35.7810486 66.7791624,40.8482546 63.6541976,43.9732194 L46.627417,61 Z",
            //         onclick: function (event) {
            //             self.doNavBack(event);
            //         }
            //     }
            // },
            iconStyle: {
                normal: {
                    color: "#FEF8EF",
                    opacity: 0.5
                }
            },
            itemSize: 18,
            showTitle:true
        },
        tooltip: {//提示框组件
            trigger: "item",
            formatter: "{b}"
        },
        geo: {//地理坐标系组件
            zoom: 1.25,//当前视角的缩放比例。
            center:[116.378398,40.251455],
            label: {
                normal: {
                    show: true,
                    textStyle: {
                        color: "white"
                    }
                },
                emphasis: {
                    show: true
                }
            },
            roam:true,
            silent:false,
            nameMap :{
                // "东城区":   " ",
                // "西城区":   " ",
                // "朝阳区":   " ",
                // "丰台区":   " ",
                // "石景山区": " ",
                // "海淀区":   " ",
                // "门头沟区": " ",
                // "房山区":   " ",
                // "通州区":   " ",
                // "顺义区":   " ",
                // "昌平区":   " ",
                // "大兴区":   " ",
                // "怀柔区":   " ",
                // "平谷区":   " ",
                // "密云区":   " ",
                // "延庆区":   " "
            },
            itemStyle: {
                normal: {
                    areaColor: normalAreaColor,
                    borderColor: "#f6f6f6"
                },
                emphasis: {
                    areaColor: emphasisAreaColor,
                    borderColor: "#f6f6f6"

                }
            },
            scaleLimit:{
                max:'3',
                min:'1.25'
            }
            // regions:
            //     [{
            //     name: "湟中县",
            //     itemStyle: {
            //         normal: {
            //            areaColor: "#3bccff"
            //         }
            //     }
            // }],
        },

        series: [
            {
                name: "显示站名",
                type: "scatter",
                coordinateSystem: "geo",//使用地理坐标系，通过 geoIndex 指定相应的地理坐标系组件
//                data: [{"name":"贵德","value":[101.434099,36.037]},{"name":"海门2","value":[94.942778,33.934588],"wiviam":"123123"}],
                symbol: "circle",//标记图形，空心圆
                symbolSize: 12,//标记的大小，可以设置成诸如 10 这样单一的数字，也可以用数组分开表示宽和高，例如 [20, 10] 表示标记宽为20，高为10。
                hoverAnimation:true,
                legendHoverLink:true,
                label: {
                    normal: {
                        formatter: "{b}",
                        position: "right",
                        show: true,//是否显示标签
                        textStyle:{
                            color:'yellow',
                            fontSize:14
                        }
                    },
                    emphasis: {
                        show: true
                    }
                },
                itemStyle: {
                    normal: {
                        color: "#f4e925",
                        shadowBlur: 13,
                        shadowColor: "#ddd"
                    }
                }
            },
            {
                name: "异常电台",
                type: "effectScatter",//涟漪特效动画的散点（气泡）图
                coordinateSystem: "geo",
                symbol: "circle",
                symbolSize: 10,

                label: {
                    normal: {
                        formatter: "{b}",
                        position: "top",
                        show: false,//是否显示标签
                        textStyle:{color:'#fff'}
                    }
                },
                itemStyle: {
                    normal: {
                        color: "#D06E1B",
                        shadowBlur: 12,
                        shadowColor: "#333"
                    }
                    // emphasis:{
                    //
                    // }
                },
                effectType:'ripple',
                effectScatter:{rippleEffect:{scale:{default: 3.5}}},
                zlevel: 1,
                showEffectOn: "render",//'render' 绘制完成后显示特效。
                rippleEffect: {//涟漪特效相关配置。
                    brushType: "stroke",//波纹的绘制方式，可选 'stroke' 和 'fill'。
                    scale:3.5
                },
                hoverAnimation: true,
                tooltip: {
//                    formatter: function(pare){
//                        console.info(pare);
//                    }
//                     formatter: "{b}"
//                     backgroundColor:'#FFCD41'
                }
            }
        ]
    };
    var arr = new Array();
    var regions1=[];
    var regions2=[];
    var Warning= [];
    var curUserCode='';
    var timer=null;

    self.getDefaultStationCodeFromParentCode = function(curStationCode){
        curUserCode = curStationCode;
        var tempStationCode="100000001001001";
        return tempStationCode;
    };

    self.init = function (parentStationCode) {
        self.myChart = echarts.init(document.getElementById("map_inner"), null, null);
        curStationCode = self.getDefaultStationCodeFromParentCode(parentStationCode);
        self.refreshNav(curStationCode);
        loadStationCfg(curStationCode);
        self.loadMap(parentStationCode);
        self.myChart.on("click", function (params) {
            if (params.componentType == "geo") {
                self.loadMapAddNav(areaCodeMap[params.name]);
            } else if (params.componentType == "series") {
                elementGroup = {};
                loadStationCfg(params.data.code);
                self.refreshNav(params.data.code);
                option.series[1].silent=true;
                option.series[0].silent=true;
                setTimeout(function(){
                    option.series[1].silent=false;
                    option.series[0].silent=false;
                    self.myChart.setOption(option);
                },2000);
            }
            self.myChart.setOption(option);
        });
    };

    self.getStationPoint = function (code) {
        if (stationInArea[code]) {
            return stationInArea[code].stations;
        }
    };

    self.loadMapAddNav = function (code) {
        self.refreshNav(code);
        self.loadMap(code);
    };

    self.refreshNav = function (code) {
        if(navStack.length > 0){
            $.each(navStack,function(i,n){
                if(n.length==code.length){
                    navStack[i]=code;
                    navStack=navStack.slice(0,i+1)
                }
            });
            var lastOne = navStack[navStack.length-1];
            if (lastOne.length < code.length) {
                navStack.push(code);
            }
            if(lastOne.length == code.length){
                navStack.pop();
                navStack.push(code);
            }
        }else{
            if(code.length != 6){
                navStack.push(self.addParentCodes(code));
            }
        }
        self.doRefreshNavHtml();
    };

    self.doRefreshNavHtml = function () {
        $("#arear_content").html(function () {
            var temp = "";
            $.each(navStack,function (i,n) {
                temp += " " + areaCodeMapReverse[n];
            });
            return temp;
        }());
    };

    self.addParentCodes = function (code) {
       if(code.length > 6){
           navStack.push(self.addParentCodes(code.substring(0,code.length -9)));
       }
       return code;
    };

    self.loadMap = function (code,message) {
        self.myChart.showLoading(myloadingCfg);
        $.get(ctxStatic + "/modules/biz/monitorCenter/map/jeoJson/100000.json?" + Math.random(), function (jeoJson) {
            echarts.registerMap(code, jeoJson);
            option.geo.map = code;
            if (self.getStationPoint(code)) {
                option.geo.label.normal.show = false;
                option.geo.label.emphasis.show = false;
                option.geo.itemStyle.emphasis.areaColor = normalAreaColor;
                option.geo.silent=true;
                clearInterval(timer);
            } else {
                option.geo.label.normal.show = true;
                option.geo.label.emphasis.show = true;
                option.geo.itemStyle.emphasis.areaColor = emphasisAreaColor;
                option.geo.silent=false;
            }
            if (typeof(message) == "undefined"){
                self.initWarningInfo(curStationCode,code);
            }
            if (message!='' && message!='undefined'){
                self.pushWarningMessage(code,message);
            }
        });
    };

    self.doNavBack = function (event) {
        var isCallBackLength = '';
        if(curUserCode.length==12){
            isCallBackLength = curUserCode.length+3;
        }else{
           isCallBackLength = curUserCode.length
        }
        if(navStack[navStack.length-1].length > isCallBackLength){
            var lastOne = navStack[navStack.length - 1];
            if (lastOne && navStack.length > 1) {
                if (event.option.geo[0].map == lastOne) {
                    navStack.pop()
                } else if (navStack.length > 1) {
                    navStack.pop()
                }
                self.loadMap(navStack[navStack.length - 1]);
            }
            self.doRefreshNavHtml();
            showMaskLayer();
        }
    };
    //请求告警信息
    self.initWarningInfo = function (curStationCode,code) {
        $.ajax({
            type: "POST",
            dataType: "json",
            data: "stationCode="+curStationCode,
            url: ctx + "/biz/basic/getExistWarningMap",
            success: function (msg) {
                if (msg) {
                    self.getAlarmStation(msg,code);//地图告警
                }
                option.series[0].data = self.getStationPoint(code);
                self.myChart.setOption(option);
                self.myChart.hideLoading();
            },
            error: function(err) {
                console.info(err);
            }
        });
    };
    //推送告警信息接收
    self.pushWarningMessage = function (code,msg) {
        if (msg) {
            self.getAlarmStation(msg,code);//地图告警
        }
        option.series[0].data = self.getStationPoint(code);
        self.myChart.setOption(option);
        self.myChart.hideLoading();
    };
    //从告警信息获取告警站点
    self.getAlarmStation = function (msg,code){
        arr=[];//在这里清空arr，防止地图告警点重复
        $.each(msg,function(i){
            if(msg[i]['2']){
                var b=i.slice(0,6);
                if (stationInArea[b]) {
                    $.each(stationInArea[b].stations,function(a){
                        if(stationInArea[b].stations[a].code==i){
                            arr.push(stationInArea[b].stations[a]);
                        }
                    });
                }
            }
        });
        // self.mapWarningData(arr,code);
        self.stationWarning(arr,code);
    };
    // 站点告警显示
    self.stationWarning = function(arr,code){
        if(code.length=='6'){
            var alarm = [];
            alarm=arr;
            // $.each(arr,function(a){
            //     if(arr[a].code && arr[a].code.slice(0,12)==code){
            //         alarm.push(arr[a])
            //     }
            // });
            option.series[1].data = alarm;
        }else{
            option.series[1].data =[];
        }
    };
    // //地图告警闪烁数据
    // self.mapWarningData = function (arr,code){
    //     Warning=[]; // 清空前面添加进来的，防止重复
    //     $.each(arr,function(a){
    //         $.each(areaCodeMapReverse,function(i,n){
    //             if(arr[a].code==i ){
    //                 if(Warning.indexOf(i.slice(0,12)) == -1){
    //                     if(code.length>=12){
    //                         Warning.push(i.slice(0,9));
    //                     }else{
    //                         Warning.push(i.slice(0,9));
    //                         Warning.push(i.slice(0,12));
    //                     }
    //                 }
    //             }
    //         })
    //     });
    //     $.each(Warning,function(i){
    //         Warning[i] = areaCodeMapReverse[Warning[i]];
    //         regions1[i]={name: Warning[i],itemStyle: {normal: {areaColor: "#3bccff"}}};
    //         regions2[i]={name: Warning[i],itemStyle: {normal: {areaColor: "#3BA7DC"}}}
    //     });
    //     if(code.length<'12'){
    //         self.mapWarning()
    //     }
    // };
    // //地图告警闪烁
    // self.mapWarning = function (){
    //     function close(){
    //         option.geo.regions=regions1;
    //     }
    //     function open(){
    //         option.geo.regions=regions2;
    //     }
    //     var isLight=true;
    //     clearInterval(timer);
    //     timer=setInterval(function(){
    //         if(isLight){
    //             close();
    //             isLight = false;
    //         }else {
    //             open();
    //             isLight = true;
    //         }
    //         self.myChart.setOption(option);
    //     },800);
    // };
};